﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;

namespace MessageRouter.ServiceBroker
{
    internal sealed class ServiceBrokerMessageReaderCommandFactory
    {
        private readonly string commandText;

        public ServiceBrokerMessageReaderCommandFactory(ServiceBrokerEndpointAddress endpointAddress, DialogLifetimePolicy dialogLifetimePolicy)
        {
            this.commandText = GetCommandText(endpointAddress, dialogLifetimePolicy);
        }

        public SqlCommand CreateCommand(SqlConnection connection)
        {
            SqlCommand command = new SqlCommand();
            command.Connection = connection;
            command.CommandType = CommandType.Text;
            command.CommandText = this.commandText;
            return command;
        }

        private string GetCommandText(ServiceBrokerEndpointAddress endpointAddress, DialogLifetimePolicy dialogLifetimePolicy)
        {
            return string.Format(@"declare @message_type_name sysname, @conversation_handle uniqueidentifier, @message_body xml; 
receive top(1)
    @conversation_handle = [conversation_handle],
    @message_type_name = [message_type_name],
    @message_body = [message_body]
from [{0}].[{1}];

select @conversation_handle, @message_type_name, @message_body where @conversation_handle is not null;

{2}", endpointAddress.SchemaName, endpointAddress.QueueName, dialogLifetimePolicy == DialogLifetimePolicy.CloseAfterReceive ? "end conversation @conversation_handle;" : string.Empty);
        }
    }
}
